#include "VSModelMeshNode.h"
#include "VSSwitchNode.h"
#include "VSGraphicInclude.h"
#include "VSModelSwitchNode.h"
#include "VSStream.h"
using namespace VSEngine2;
IMPLEMENT_RTTI(VSModelMeshNode,VSMeshNode)
BEGIN_ADD_PROPERTY(VSModelMeshNode,VSMeshNode)
REGISTER_PROPERTY(m_uiLodType,LodType,VSProperty::F_SAVE_LOAD_CLONE)
END_ADD_PROPERTY
IMPLEMENT_INITIAL_BEGIN(VSModelMeshNode)
IMPLEMENT_INITIAL_END
VSModelMeshNode::VSModelMeshNode()
{
	m_uiLodType = 0;
	m_bIsNeedDraw = true;
}
VSModelMeshNode::~VSModelMeshNode()
{

}
unsigned int VSModelMeshNode::DiskUse()const
{
	unsigned int Used = VSNode::DiskUse();
	Used += VSResource::DiskUse();
	Used += sizeof(unsigned int);

	return Used;
}
bool VSModelMeshNode::Save(VSStream & rStream,unsigned int &iSaveUse)const
{
	if(!VSNode::Save(rStream,iSaveUse))
		return 0;

	if (!VSResource::Save(rStream,iSaveUse))
	{
		return false;
	}
	if(!rStream.Write(&m_uiLodType,sizeof(unsigned int)))
		return 0;
	iSaveUse += sizeof(unsigned int);

	return 1;
}
bool VSModelMeshNode::Load(VSStream & rStream,unsigned int &iSaveUse)
{	
	if(!VSNode::Load(rStream,iSaveUse))
		return 0;
	if (!VSResource::Load(rStream,iSaveUse))
	{
		return 0;
	}
	if(!rStream.Read(&m_uiLodType,sizeof(unsigned int)))
		return 0;
	iSaveUse += sizeof(unsigned int);


	return 1;
}
VSGeometryNode * VSModelMeshNode::GetGeometryNode(unsigned int uiLodLevel)
{
	if (m_pChild.GetNum() > 1)
	{
		return NULL;
	}
	else
	{
		VSModelSwitchNode* Temp = DynamicCast<VSModelSwitchNode>(m_pChild[0]);
		if (!Temp)
		{
			VSGeometryNode * pGeometryNode = DynamicCast<VSGeometryNode>(m_pChild[0]);
			return pGeometryNode;
		}
		else
		{
			return	Temp->GetGeometryNode(uiLodLevel);
		}
	}
}
bool VSModelMeshNode::Clone(const VSObject *pObject,unsigned int uiType)
{
	const VSModelMeshNode* Temp = DynamicCast<VSModelMeshNode>(pObject); 
	if(!Temp)
		return 0;
	if(VSMeshNode::Clone(pObject,uiType))
	{
		m_uiLodType = Temp->m_uiLodType;
		return 1;

	}
	else
	{
		return 0;
	}

}
void VSModelMeshNode::CreateClodMesh()
{
	if (m_uiLodType != LT_CLOD)
	{
		return;
	}
	VSNode::CreateClodMesh();
}
bool VSModelMeshNode::SetLodDesirePercent(VSREAL fDesirePercent)
{
	if (m_uiLodType == LT_NONE)
	{
		return false;
	}
	if (!VSSpatial::SetLodDesirePercent(fDesirePercent))
	{
		return false;
	}
	for(unsigned int i = 0 ; i < m_pChild.GetNum() ; i++)
	{

		if(!m_pChild[i]->SetLodDesirePercent(fDesirePercent))
			return false;

	}
	return true;
}
VSSwitchNode * VSModelMeshNode::GetDlodNode()const
{
	if (m_pChild.GetNum())
	{
		return DynamicCast<VSSwitchNode>(m_pChild[0]);
	}
	return NULL;
}